'use strict'

define(['jquery' , 'qrcode', 'countUp', 'bootstrap'] , function($, QRCodeJs, CountUp) {
  return {
  init : function(data){
    var that = this;
    var message = "初始化测试二维码"
    var date = new Date();
    var siteId = data.siteId;
    var qrcode = new QRCode("qrcode", {
      text: siteId + '|' + date.getTime(),
      width: 260,
      height: 260,
      colorDark : "#000000",
      colorLight : "#ffffff",
      correctLevel : QRCode.CorrectLevel.H
    });
    that.qrcode = qrcode;
    that.qrcodeText = siteId + '|' + date.getTime();
    that.siteId = siteId;
    that.qrcode.clear();
    that.initPorgressBar();
    that.generateQrcode(siteId);
    that.showSigninResult();
    that.rebuild();
//      var res = {"code":"0","message":"获取数据成功","data":{"signinRecord":{"id":214,"courseSchedule":73444,"siteId":4,"studentName":"郭璐","coachName":"徐敏敏","coachAvatar":"FrSgPeWAnoYtJ4w7b0nsFD0SEx5g.jpg","duration":8,"training":null,"firstDate":1537113600000,"latestDate":null,"bfrTarget":null,"bfrCompletionRate":0,"weightTarget":null,"weightCompletionRate":0,"target":null,"targetType":null,"totalReduce":25204.00,"personalReduce":3.10,"finishHour":8,"avgGrade":null,"currentRank":2,"showed":true,"message":"4|1539863909488","crateTime":1539863921000,"firstTime":"2018-09-17","latestTime":null},"digital":false,"courseName":"线下1v1","couldEdit":false,"courseSchedule":{"id":73444,"sequence":0,"student":10929,"coach":92,"course":15,"site":4,"courseRound":16412,"courseType":"INDIVIDUAL","occurDate":"2018-10-18","occurHour":"20:00","roomSchedule":60528,"roomType":"ROOM","scheduleStatus":"FINISH","comment":null,"grade":null,"signinTime":1539863947000,"disabled":false,"siteName":"南翔五彩城店","coachName":"徐敏敏","signinStartTime":1539860400000,"signinEndTime":1539871200000}}}
//      var data = res.data;
//        that.showResult(data);
    that.showQrcodeText();
  },
  
  initPorgressBar: function() {
    var dataval = parseInt($('.target-progress').attr("data-amount"));
    if (dataval < 100) {
        $('.target-progress .amount').css("width", 100 - dataval + "%");
    }
  /*FOR DEMO ONLY*/
    $('#increase').click(function () {
        modifyProgressVal(1);
    });
    $('#decrease').click(function () {
        modifyProgressVal(-1);
    });
    function modifyProgressVal(type) {
        dataval = parseInt($('.target-progress').attr("data-amount"));
        if (type == 1) dataval = Math.min(100,dataval + 10)
        else if (type == -1) dataval = Math.max(0,dataval - 10);
        $('.target-progress .amount').css("width", 100 - dataval + "%");
        $('.target-progress').attr("data-amount", dataval);
    }
  },
  
  generateQrcode: function() {
    var that = this;
    window.openQrcode = function() {
      var time = 60;
      var message = "二维码有效期" + time + "秒"
      var date = new Date();
      clearInterval(that.timer);
      that.qrcode.clear();
      that.qrcode.makeCode(that.siteId + '|' + date.getTime());
      that.qrcodeText = that.siteId + '|' + date.getTime();
      
      $(".qrcode-desc").html(message);
      that.timer = setInterval(function(){
        time--;
        message = "二维码有效期" + time + "秒";
        $(".qrcode-desc").html(message);
        
        if(time % 5 == 0) {
          console.log(time);
          window.opener.requestSignData();
        }
        
        if(time==1){                                                                              //当num变为1的时候，通过 clearInterval()结束倒计时
          clearInterval(that.timer);
          message = "二维码已失效，请管理员重新刷新";
          $(".qrcode-desc").html(message);
        }
      }, 1000)
      
    }
  },
  
  rebuild: function() {
    var that = this;
    window.rebuild = function() {
      setTimeout(function(){
        window.location.reload()
      }, 5000)
    }
  },
  
  showSigninResult: function() {
    var that = this;
    window.showSigninResult = function(data) {
      console.log(data);
      that.showResult(data);
    }
  },
  
  showResult: function(data) {
    var that = this;
    
    $(".welcome-body").addClass("hide");
    $(".signin-info").removeClass("hide");
    
    $(".studentName").html(data.signinRecord.studentName);
    $(".coachName").html(data.signinRecord.coachName);
    $(".duration").html(data.signinRecord.duration + "&nbsp;<span style='font-size: 20px;'>课时</span>");
    $(".training").html(data.signinRecord.training);
    if(data.signinRecord.coachAvatar) {
    	$(".coachAvatar").attr("src", "http://prod.qiniu.fit-start.co/" + data.signinRecord.coachAvatar)
    }
    $(".firstTime").html(data.signinRecord.firstTime);
    if(!data.signinRecord.latestTime) {
    	$('.progress-right').addClass("hide");
    } else {
    	$(".latestTime").html(data.signinRecord.latestTime);
    }
//    $(".target-desc").html(data.signinRecord.target);
    
    if(data.digital == true) {
    	var targetType = data.signinRecord.targetType;
    	if(targetType == 'WEIGHT_LOSING') {
    		$(".target-progress").attr("data-amount", data.signinRecord.weightCompletionRate < 0 ? 0 : data.signinRecord.weightCompletionRate);
        	$(".target-progress").attr("data-name", data.signinRecord.weightTarget)
        	$(".target-progress-two").addClass("hide");
        	$(".progress-left").addClass("single-progress");
        	$(".progress-right").addClass("single-progress");
    	} else {
    		if(targetType == 'BODY_FAT_RATE_REDUCING' && !data.signinRecord.weightTarget) {
    			$(".target-progress").attr("data-amount", data.signinRecord.bfrCompletionRate < 0 ? 0 : data.signinRecord.bfrCompletionRate);
            	$(".target-progress").attr("data-name", data.signinRecord.bfrTarget)
            	$(".target-progress-two").addClass("hide");
            	$(".progress-left").addClass("single-progress");
            	$(".progress-right").addClass("single-progress");
    		} else {
    			$(".target-progress").attr("data-amount", data.signinRecord.weightCompletionRate < 0 ? 0 : data.signinRecord.weightCompletionRate);
            	$(".target-progress").attr("data-name", data.signinRecord.weightTarget)
            	$(".target-progress-two").attr("data-amount", data.signinRecord.bfrCompletionRate < 0 ? 0 : data.signinRecord.bfrCompletionRate);
            	$(".target-progress-two").attr("data-name", data.signinRecord.bfrTarget)
            	$(".progress-left").addClass("double-progress");
            	$(".progress-right").addClass("double-progress");
    		}
    	}
    	console.log($(".target-progress").data("amount"))
//    	$(".totalDesc").html(data.targetTypeDescription);
    	
    	var options = {
        useEasing: true, 
        useGrouping: true, 
        separator: ',', 
        decimal: '.', 
      };
    	var end = parseFloat(data.signinRecord.totalReduce);
      var personal = (!data.signinRecord.personalReduce) ? parseFloat(0) : parseFloat(data.signinRecord.personalReduce);
      var start = end - personal;
      console.log(start)
      console.log(end)
    	var demo = new CountUp('totalReduce', start, end, 1, 3, options);
    	if (!demo.error) {
    	  demo.start();
    	} else {
    	  console.error(demo.error);
    	}
    	$(".totalReduce").html(data.signinRecord.totalReduce);
//    	$(".totalUnit").html(data.targetTypeUnit);
    	if(data.signinRecord.personalReduce) {
    		$(".personalReduce").html(data.signinRecord.personalReduce);
    	}
//    	$(".personalUnit").html(data.targetTypeUnit);
    } else {
    	$(".target-progress").data("amount", 100);
    	$(".target").addClass("hide");
//    	$(".total-stat").addClass("hide");
//    	$(".personal-stat").addClass("hide");
    }
    
    $(".finishHour").html(data.signinRecord.finishHour);
    $(".currentRank").addClass("pointer-"+ data.signinRecord.currentRank);
    $(".course-process").html(parseInt(data.signinRecord.currentRank) * 10);
    var i = 0;
    $(".stars").find("li").each(function(){
      i = i + 2;
      var rest = data.signinRecord.avgGrade - i;
      if(rest >= 0) {
        $(this).addClass("star-full");
      } else if(rest == -1) {
        $(this).addClass("star-harf");
      } else if (rest <= -2) {
        $(this).addClass("star-empty");
      }
      
      console.log($(this));
    })
    var dataval = parseInt($('.target-progress').attr("data-amount"));
    console.log(dataval)
    if (dataval < 100) {
    	var result = 100-dataval;
      $('.target-progress .amount').css("width", result + "%");
    } else {
      $('.target-progress .amount').css("width", "0%");
    }
    
    var datavalTwo = parseInt($('.target-progress-two').attr("data-amount"));
    if (datavalTwo < 100) {
    	var result = 100-datavalTwo;
        $('.target-progress-two .amount-two').css("width", result + "%");
    } else {
      $('.target-progress .amount').css("width", "0%");
    }
    
  },
  
  showQrcodeText: function() {
	  var that = this;
	    window.showQrcodeText = function() {
	    	return that.qrcodeText;
	    }
	  
  }
  }
})